<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="70%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '170px' : '140px'"
    >
      <!-- <el-color-picker v-model="domain.tagsColor">
            </el-color-picker> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="dataForm.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="dataForm.realName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="密码"
            prop="password"
            :class="{ 'is-required': !dataForm.id }"
          >
            <el-input v-model="dataForm.password" type="password"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="dataForm.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="dataForm.gender">
              <el-radio :label="0">{{ $t("user.gender0") }}</el-radio>
              <el-radio :label="1">{{ $t("user.gender1") }}</el-radio>
              <el-radio :label="2">{{ $t("user.gender2") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="0">{{ $t("user.status0") }}</el-radio>
              <el-radio :label="1">{{ $t("user.status1") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="dataForm.mobile"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import { isEmail, isMobile } from "@/utils/validate";

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: "",
        username: "",
        realName: "",
        mobile: "",

        email: "",
        gender: null,
        status: null,
        password: "",
      },
      tempRealName: "",
      tempMobile: "",
    };
  },
  computed: {
    dataRule() {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        callback();
      };

      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.email") })
            )
          );
        }
        callback();
      };
      var validateMobile = (rule, value, callback) => {
        if (value.indexOf("**") > -1) {
          value = value.replace(/\*/g, "5");
        }
        if (!isMobile(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.mobile") })
            )
          );
        }
        callback();
      };
      return {
        username: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        gender: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],

        password: [
          { validator: validatePassword, trigger: "blur" },
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],

        realName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
          { validator: validateEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
          { validator: validateMobile, trigger: "blur" },
        ],
      };
    },
  },
  methods: {
    handleAvatarSuccess() {},
    beforeAvatarUpload() {},
    init() {
      console.log(this.dataForm);
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/hotel/staff/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          console.log(res.data);
          this.tempRealName = this.dataForm.realName;
          this.tempMobile = this.dataForm.mobile;
          console.log(this.tempRealName);
          console.log(this.tempMobile);
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          //加密
          let newDataForm = Object.assign({}, this.dataForm);
          if (
            !newDataForm.realName ||
            this.tempRealName != newDataForm.realName
          ) {
            //编辑了
            newDataForm.realName = this.$CryptoJS.encrypt(newDataForm.realName);
          } else {
            //没编辑传null
            newDataForm.realName = null;
          }
          if (!newDataForm.mobile || this.tempMobile != newDataForm.mobile) {
            newDataForm.mobile = this.$CryptoJS.encrypt(newDataForm.mobile);
          } else {
            newDataForm.mobile = null;
          }
          this.$http[!newDataForm.id ? "post" : "put"]("/hotel/staff", {
            ...newDataForm,
            homestayId: this.$store.state.user.homestayId,
          })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
<style scoped lang="scss">
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .el-upload:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 158px;
    height: 158px;
    line-height: 158px;
    text-align: center;
  }

  .avatar {
    width: 158px;
    height: 158px;
    display: block;
  }
}

h3 {
  padding: 30px 0 15px;
  width: 94%;
  margin: 0 auto 30px;
  border-bottom: 1px solid #ddd;
  color: #303133;
  font-size: 22px;
  overflow: hidden;
}
</style>
